package com.nimitz.web.controller.maintenance;

import com.nimitz.common.core.controller.BaseController;
import com.nimitz.common.core.domain.AjaxResult;
import com.nimitz.common.core.domain.entity.SysUser;
import com.nimitz.common.core.page.TableDataInfo;
import com.nimitz.common.utils.SecurityUtils;
import com.nimitz.maintenance.service.impl.MaintenanceNumberGeneratorService;
import com.nimitz.maintenance.domain.Maintenance;
import com.nimitz.maintenance.service.MaintenanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/smart/maintenance")
public class MaintenanceController extends BaseController{
    @Autowired
    private MaintenanceService maintenanceService;
    @Autowired
    private MaintenanceNumberGeneratorService maintenanceNumberGeneratorService;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('smart:maintenance:list')")
    public TableDataInfo selectAll(@RequestParam(required=false) Long kahunaId, @RequestParam(required=false) String state){
        startPage();
        List<Maintenance> maintenances = maintenanceService.selectAll(kahunaId,state);
        return getDataTable(maintenances);
    }

    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('smart:maintenance:add')")
    public AjaxResult addMaintenance(@RequestBody Maintenance maintenance){
        Long userId = SecurityUtils.getUserId();
        maintenance.setCreateBy(userId);
        maintenance.setUpdateBy(userId);
        String maintenanceId = maintenanceNumberGeneratorService.generateOrderNumber();
        maintenance.setMaintenanceId(maintenanceId);
        maintenanceService.addMaintenance(maintenance);
        return AjaxResult.success();
    }

    @PutMapping("/update")
    @PreAuthorize("@ss.hasPermi('smart:maintenance:edit') or @ss.hasPermi('smart:maintenance:edit1')")
    public AjaxResult updateMaintenance(@RequestBody Maintenance maintenance){
        Long userId = SecurityUtils.getUserId();
        maintenance.setUpdateBy(userId);
        maintenanceService.updateMaintenance(maintenance);
        return AjaxResult.success();
    }

    @GetMapping("/select")
    @PreAuthorize("@ss.hasPermi('smart:maintenance:edit')")
    public AjaxResult selectMaintenanceById(@RequestParam Long id){
        Maintenance maintenance = maintenanceService.selectMaintenance(id);
        return AjaxResult.success(maintenance);
    }

    @PutMapping("/delete")
    @PreAuthorize("@ss.hasPermi('smart:maintenance:remove')")
    public AjaxResult deleteMaintenance(@RequestParam Long id){
        maintenanceService.deleteMaintenance(id);
        return AjaxResult.success();
    }

    @GetMapping("/lookFor")
    public AjaxResult selectByRoleId(){
        List<SysUser> list = maintenanceService.selectByRoleId();
        return AjaxResult.success(list);
    }
}
